package com.xxm.camera.camera2

import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCaptureSession.StateCallback
import android.hardware.camera2.CameraDevice
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import android.view.View
import android.view.WindowManager.LayoutParams
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.xxm.R
import com.xxm.databinding.ActivityCamera2Binding
import com.xxm.databinding.ActivityCameraxBinding
import com.xxm.mediacodec.MediaCodecModel
import com.zhangws.comman.base.BaseActivity

/**
 *Time:2023/6/13
 *Author:zhangwenshuan
 *Description:
 *since version
 *
 */
class Camera2Activity : BaseActivity<ActivityCamera2Binding>(), CameraCallback {
    private val model by lazy {
        ViewModelProvider(this)[Camera2Model::class.java]
    }

    private lateinit var adapter: Camera2Adapter

    private val previewWidth by lazy {
        resources.displayMetrics.widthPixels / 3
    }

    override fun getViewDataBinding(): ActivityCamera2Binding = DataBindingUtil.setContentView(this, R.layout.activity_camera2)

    override fun initView() {
        if (model.isSupportCamera()) {
            viewBinding.tvInfo.visibility = View.GONE
        } else {
            viewBinding.tvInfo.text = "未检测到摄像头"
        }

        adapter = Camera2Adapter()
        viewBinding.rvCamera.layoutManager = LinearLayoutManager(this)
        viewBinding.rvCamera.adapter = adapter

        model.cameraCallback=this
    }

    override fun initListener() {
        adapter.addOnItemChildClickListener(R.id.btnStart) { adapter, view, position -> model.openCamera(adapter.items[position].id) }
        adapter.addOnItemChildClickListener(R.id.btnStop) { adapter, view, position -> model.closeCamera(adapter.items[position]) }
    }

    override fun initData() {
        model.cameraInfo.observe(this) {
            adapter.submitList(it)
        }

        model.getCameraListInfo()
    }
    private  val TAG = "Camera2"
    override fun onCameraOpen(camera: NCameraInfo) {
        adapter.notifyItemChanged(adapter.items.indexOf(camera))
        val textureView = TextureView(this)
        textureView.id = View.generateViewId()
        camera.previewId=textureView.id
        Log.d(TAG,"onCameraOpen:${camera}")
        val layoutParams = LinearLayout.LayoutParams(previewWidth, LayoutParams.MATCH_PARENT)
        viewBinding.llCameraPreview.addView(textureView, layoutParams)

        textureView.surfaceTextureListener=object:SurfaceTextureListener{
            override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
                Log.d(TAG,"onSurfaceTextureAvailable")
                val surface = Surface(textureView.surfaceTexture)
                val builder = camera.cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)!!
                builder.addTarget(surface)
                camera.cameraDevice?.createCaptureSession(listOf(surface), object : StateCallback() {
                    override fun onConfigured(session: CameraCaptureSession) {
                        session.setRepeatingRequest(builder.build(),null,model.handler)
                    }

                    override fun onConfigureFailed(session: CameraCaptureSession) {

                    }
                }, model.handler)
            }

            override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
                Log.d(TAG,"onSurfaceTextureSizeChanged")
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                Log.d(TAG,"onSurfaceTextureDestroyed")
                return true
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
                //Log.d(TAG,"onSurfaceTextureUpdated")
            }
        }


    }

    override fun onCameraClose(camera: NCameraInfo) {
        Log.d(TAG,"onCameraClose:${camera}")
        adapter.notifyItemChanged(adapter.items.indexOf(camera))
        camera.cameraDevice?.close()
        val view=viewBinding.llCameraPreview.findViewById<TextureView>(camera.previewId)
        viewBinding.llCameraPreview.removeView(view)
    }

    override fun onCameraError(camera: NCameraInfo, error: Int) {
        Log.e(TAG,"onCameraError:${camera}，${error}")
        adapter.notifyItemChanged(adapter.items.indexOf(camera))
        camera.cameraDevice?.close()
    }

    override fun onDestroy() {
        super.onDestroy()
        adapter.items.forEach {
            it.cameraDevice?.close()
        }
    }
}